<template>
  <div class="add-or-edit">
    <Button type="primary" @click="handleClick">{{ isEdit?'编辑':'新增' }}</Button>
    <el-dialog :visible.sync="visible" :close-on-click-modal="false" :title="isEdit?'编辑':'新增'" @close="handleClose">
      <FormContainer :column="2">
        <el-form ref="form" :model="formData" :rules="formRules" :close-on-click-modal="false" label-width="130px">
          <el-form-item prop="postCode" label="岗位">
            <SelectForDict :code.sync="formData.postCode" :name.sync="formData.postName" dict-type-code="DEPT_POST_CODE" placeholder="请选择岗位" clearable filterable></SelectForDict>
          </el-form-item>
          <el-form-item prop="dept" label="责任部门">
            <SelectForDict
              dict-type-code="RESPONSIBLE_DEPARTMENT"
              placeholder="请选择责任部门"
              bind-name="dictName"
              bind-value="dictCode"
              filterable
              clearable
              :code.sync="formData.dept"
              :name.sync="formData.deptName"
              @update:code="handleDeptChange"
            ></SelectForDict>
          </el-form-item>
          <el-form-item prop="qupOrganization" label="QUP组织">
            <SearchSelectPicker
              :url="'/call-center/api/v1/staffInfo/remoteOrg/' + formData.dept + '/page'"
              placeholder="请选择QUP组织"
              lable-name="orgName"
              value-name="orgCode"
              :readonly="!formData.dept"
              :disabled="!formData.dept"
              must-pid
              :parent-id="formData.dept"
              :lable.sync="formData.qupOrganizationName"
              :value.sync="formData.qupOrganization"
              @selectChange="handleOrgChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="receiver" label="用户">
            <SearchSelectPicker
              :url="'/call-center/api/v1/staffInfo/user/org/' + formData.qupOrganization"
              placeholder="请选择用户"
              lable-name="userName"
              value-name="account"
              :readonly="!formData.qupOrganization"
              :disabled="!formData.qupOrganization"
              must-pid
              :parent-id="formData.qupOrganization"
              :value.sync="formData.receiver"
              :lable.sync="formData.receiverName"
              @selectChange="handleReceiverChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="receiverPhone" label="联系电话">
            <el-input v-model="formData.receiverPhone" :disabled="!formData.qupOrganization" clearable placeholder="请输入联系电话" :maxlength="11" />
          </el-form-item>
          <el-form-item prop="officeCode" label="办事处名称">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/office/ref/page"
              placeholder="请选择办事处"
              lable-name="name"
              value-name="code"
              method="get"
              :value.sync="formData.officeCode"
              :lable.sync="formData.officeName"
              @selectChange="handleOfficeSelectChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="customCode" label="经销商/三方物流名称">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/dealer/ref/page"
              method="get"
              placeholder="请选择经销商/三方物流名称"
              :params="{query:{officeCode:formData.officeCode},type:0}"
              lable-name="name"
              value-name="code"
              custom-name="codeOrName"
              :parent-id="formData.officeCode"
              :value.sync="formData.customCode"
              :lable.sync="formData.customName"
              :disabled="!formData.officeCode"
              clearable
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="platformCode" label="电商平台">
            <SearchSelectPicker
              url="/select-service/api/v1/eco/platform/page"
              placeholder="请选择"
              lable-name="name"
              value-name="code"
              :value.sync="formData.platformCode"
              :lable.sync="formData.platformName"
              @selectChange="handlePlatformChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="storeCode" label="电商店铺">
            <SearchSelectPicker
              url="/select-service/api/v1/eco/shop/page"
              placeholder="请选择"
              lable-name="name"
              value-name="code"
              must-pid
              :parent-id="formData.platformCode"
              :disabled="!formData.platformCode"
              :params="{query:{platformCode:formData.platformCode},type:0}"
              :value.sync="formData.storeCode"
              :lable.sync="formData.storeName"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="provinceCode" label="省">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/adminidiv"
              :remote="false"
              placeholder="请选择"
              lable-name="name"
              value-name="id"
              method="get"
              :value.sync="formData.provinceCode"
              :lable.sync="formData.provinceName"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item :span="24">
            <div style="text-align: right;">
              <Button type="default" @click="handleCancel">取消</Button>
              <Button type="primary" @click="handleSave">保存</Button>
            </div>
          </el-form-item>
        </el-form>
      </FormContainer>
    </el-dialog>
  </div>
</template>
<script>
import FormContainer from '@/components/FormContainer'
import SelectForDict from '@/components/SelectForDict'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import { create, update } from '@/api/ecRecipientConfig'
export default {
  name: 'AddOrEdit',
  components: {
    FormContainer,
    SelectForDict,
    SearchSelectPicker
  },
  props: {
    selection: {
      type: Array,
      default: () => []
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validatorPhone = (r, v, c) => {
      if (/^(1\d{10})|(\d{7,8})|(\d{3,4}-?\d{7,8})$/.test(v)) {
        c()
      } else {
        c(new Error('联系电话格式不正确'))
      }
    }
    return {
      visible: false,
      formData: {
        postCode: '',
        postName: '',
        dept: '',
        deptName: '',
        qupOrganizationName: '',
        qupOrganization: '',
        receiver: '',
        receiverName: '',
        receiverPhone: '',
        officeCode: '',
        officeName: '',
        customCode: '',
        customName: '',
        platformCode: '',
        platformName: '',
        storeCode: '',
        storeName: '',
        provinceCode: '',
        provinceName: ''
      },
      formRules: {
        postCode: [{ required: true, message: '请选择岗位', trigger: 'change' }],
        dept: [{ required: true, message: '请选择责任部门', trigger: 'change' }],
        qupOrganization: [{ required: true, message: '请选择QUP组织', trigger: 'change' }],
        receiver: [{ required: true, message: '请选择用户', trigger: 'change' }],
        receiverPhone: [
          { required: true, message: '请输入联系电话', trigger: 'change' },
          { validator: validatorPhone, trigger: 'change' }
        ]
        // officeCode: [{ required: true, message: '请选择办事处', trigger: 'change' }],
        // customCode: [{ required: true, message: '请选择经销商/三方物流名称', trigger: 'change' }],
        // platformCode: [{ required: true, message: '请选择电商平台', trigger: 'change' }],
        // storeCode: [{ required: true, message: '请选择电商店铺', trigger: 'change' }]
      }
    }
  },
  computed: {
    detail() {
      return this.isEdit && this.selection instanceof Array && this.selection.length > 0 ? this.selection[0] : {}
    },
    secondBTpe() {
      const t = this.formData
      const t1 = t.channel !== undefined && t.businessType !== undefined && t.channel !== '' && t.businessType !== ''
      return t1 ? `${t.channel}-${t.businessType}` : undefined
    }
  },
  watch: {
    visible: {
      handler(v) {
        this.formDataInit()
      },
      immediate: true
    }
  },
  methods: {
    handleDeptChange() {
      this.$set(this.formData, 'qupOrganizationName', '')
      this.$set(this.formData, 'qupOrganization', '')
      this.handleOrgChange()
    },
    handleOrgChange() {
      this.$set(this.formData, 'receiver', '')
      this.$set(this.formData, 'receiverName', '')
      this.$set(this.formData, 'receiverPhone', '')
    },
    handleReceiverChange(v) {
      // 设置电话号码
      this.$set(this.formData, 'receiverPhone', (v || {}).phone || '')
    },
    handleOfficeSelectChange() {
      this.$set(this.formData, 'customCode', '')
      this.$set(this.formData, 'customName', '')
    },
    handlePlatformChange() {
      this.$set(this.formData, 'storeCode', '')
      this.$set(this.formData, 'storeName', '')
    },
    handleClick() {
      if (this.isEdit) {
        if (this.selection.length > 1) {
          this.$message.warning(`该操作只能单选`)
          return
        } else if (this.selection.length === 0) {
          this.$message.warning(`请选择【编辑】项`)
          return
        }
      }
      this.visible = true
    },
    handleCancel() {
      this.visible = false
    },
    handleSave() {
      return this.$refs.form.validate().then(() => {
        return this.saveData()
      })
    },
    handleClose() {
      const form = this.$refs.form
      form && form.resetFields()
      for (const k of Object.keys(this.formData)) {
        // this.$set(this.formData, k, '')
        this.formData[k] = ''
      }
    },
    saveData() {
      const ajax = this.isEdit ? update : create
      const data = {}
      if (this.isEdit) {
        Object.assign(data, this.detail)
      }
      Object.assign(data, this.formData)
      return ajax(data).then(res => {
        this.$message.success('操作成功!')
        this.visible = false
        this.$emit('on-refresh', this.isEdit ? 'onPage' : 'opCondition')
      })
    },
    formDataInit() {
      if (this.isEdit) {
        for (const k of Object.keys(this.formData)) {
          const v = this.detail[k]
          this.$set(this.formData, k, v === undefined || v === null ? '' : v)
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.add-or-edit{
  display: inline-block;
  margin-right: 10px;
}
</style>
